﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using System.Windows.Browser;
using System.Windows.Markup;
using System.ComponentModel;

namespace GreetingCreator
{
    [TemplatePart(Name = "PART_CaptchaContainer", Type = typeof(ContentControl))]
    [TemplatePart(Name = "PART_CaptchaInput", Type = typeof(TextBox))]
    [TemplatePart(Name = "PART_ReloadButton", Type = typeof(Button))]
    [TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
    [TemplateVisualState(Name = "Updating", GroupName = "CommonStates")]
    public class CaptchaControl : Control, INotifyPropertyChanged
    {
        #region Fields

        private ContentControl _captchaContainer = null;
        private TextBox _captchaInput = null;
        private Button _reloadButton = null;

        #endregion Fields
        #region Constructors

        public CaptchaControl()
        {
            this.DefaultStyleKey = typeof(CaptchaControl);
            this.Loaded += new RoutedEventHandler(OnCaptchaControlLoaded);
            this.InfoText = "Type the 4 characters above:";
            this.ReloadText = "Reload captcha";
        }

        private void OnCaptchaControlLoaded(object sender, RoutedEventArgs e)
        {
            if (HtmlPage.IsEnabled)
            {
                InitializeCaptcha();
            }
        }

        #endregion Constructors
        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion INotifyPropertyChanged
        #region Properties

        public static readonly DependencyProperty ReloadTextProperty = DependencyProperty.Register("ReloadText", typeof(string), typeof(CaptchaControl), new PropertyMetadata(OnReloadTextPropertyChanged));
        public string ReloadText
        {
            get { return (string)GetValue(ReloadTextProperty); }
            set { SetValue(ReloadTextProperty, value); }
        }

        private static void OnReloadTextPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            CaptchaControl control = sender as CaptchaControl;
            if (control != null)
            {
                control.NotifyPropertyChanged("ReloadText");
            }
        }

        public static readonly DependencyProperty InfoTextProperty = DependencyProperty.Register("InfoText", typeof(string), typeof(CaptchaControl), new PropertyMetadata(OnInfoTextPropertyChanged));
        public string InfoText
        {
            get { return (string)GetValue(InfoTextProperty); }
            set { SetValue(InfoTextProperty, value); }
        }

        private static void OnInfoTextPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            CaptchaControl control = sender as CaptchaControl;
            if (control != null)
            {
                control.NotifyPropertyChanged("InfoText");
            }
        }

        public string CaptchaAnswer
        {
            get
            {
                if (_captchaInput == null)
                {
                    return string.Empty;
                }
                return _captchaInput.Text;
            }
        }

        #endregion Properties

        public override void OnApplyTemplate()
        {
            this._captchaContainer = this.GetTemplateChild("PART_CaptchaContainer") as ContentControl;
            if (_captchaContainer == null)
            {
                throw new NullReferenceException("Could not find templated PART: PART_CaptchaContainer");
            }

            this._captchaInput = this.GetTemplateChild("PART_CaptchaInput") as TextBox;
            if (_captchaInput == null)
            {
                throw new NullReferenceException("Could not find templated PART: PART_CaptchaInput");
            }

            this._reloadButton = this.GetTemplateChild("PART_ReloadButton") as Button;
            if (_reloadButton == null)
            {
                throw new NullReferenceException("Could not find templated PART: PART_ReloadButton");
            }
            _reloadButton.Click += new RoutedEventHandler(OnReloadButtonClick);

            base.OnApplyTemplate();
        }        


        private void InitializeCaptcha()
        {
            RequestCaptcha();
        }

        private void RequestCaptcha()
        {
            VisualStateManager.GoToState(this, "Updating", false);

            GreetingServiceReference.GreetingServiceClient client = new GreetingServiceReference.GreetingServiceClient("BasicHttpBinding_IGreetingService");
            client.GetCaptchaCompleted += new EventHandler<GreetingCreator.GreetingServiceReference.GetCaptchaCompletedEventArgs>(OnGetCaptchaCompleted);

            client.GetCaptchaAsync();
        }

        private void OnGetCaptchaCompleted(object sender, GreetingCreator.GreetingServiceReference.GetCaptchaCompletedEventArgs e)
        {            
            UIElement content = (UIElement)XamlReader.Load(e.Result.XAML);
            
            if (_captchaContainer != null)
            {
                _captchaContainer.Content = content;
            }

            VisualStateManager.GoToState(this, "Normal", false);            
        }        

        private void OnReloadButtonClick(object sender, RoutedEventArgs e)
        {
            Reload();
        }

        public void Reload()
        {
            _captchaInput.Text = string.Empty;
            RequestCaptcha();
        }
    }
}
